<template>

	<el-dialog v-model="dialogVisible" :title="dialogTitle" :before-close="closeDialog" class="elDiaLog" lock-scroll
		width="1000px" :close-on-click-modal="false" :close-on-press-escape="false">

		<div class="form-box" v-if="['act_edit','act_add'].includes(dialogStatus)" v-loading="loading2">
		
			<el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="150px">
				<el-form-item required label="合同名称" prop="contract_id">
					<div class="" v-if="formData.contract_id">
						<el-text style="margin-right: 10px;" type="primary">{{selectRow.title}}</el-text>
						<el-button @click="bindGongCheng" circle>
							<template #icon><i-ep-position /></template>
						</el-button>
					</div>
					<el-button v-else type="primary" @click="bindGongCheng">绑定合同</el-button>
				</el-form-item>
				<el-form-item required label="申请人" prop="uid">

					<el-tree-select v-model="formData.uid" :data="options" node-key="id" check-strictly
						:render-after-expand="false" :default-expanded-keys="[1]" style="width: 100%"
						placeholder="请选择审核人" :props="{
							label: 'name',
							children: 'children',
							value: 'uid',
							'disabled':'disable'
						}">
						<template #default="{ node, data }">
							<div class="lineDiv">
								<div v-if="!data.disable" class="lineimgs">
									<img class="lineimg" style="width: 20px;height: 20px;" :src="data.avatar" alt="">
								</div>
								<div class="lineTx">
									{{ node.label }}
								</div>
							</div>
						</template>
					</el-tree-select>
				</el-form-item>
				<el-form-item required label="审核人" prop="check_uid">
					<el-tree-select v-model="formData.check_uid" :data="options" node-key="id" check-strictly
						:render-after-expand="false" :default-expanded-keys="[1]" style="width: 100%"
						placeholder="请选择审核人" :props="{
							label: 'name',
							children: 'children',
							value: 'uid',
							'disabled':'disable'
						}">
						<template #default="{ node, data }">
							<div class="lineDiv">
								<div v-if="!data.disable" class="lineimgs">
									<img class="lineimg" style="width: 20px;height: 20px;" :src="data.avatar" alt="">
								</div>
								<div class="lineTx">
									{{ node.label }}
								</div>
							</div>
						</template>
					</el-tree-select>

				</el-form-item>
				<el-form-item required label="借阅时间" prop="add_time">
					<el-date-picker v-model="formData.add_time" 
									type="datetime" 
									format="YYYY-MM-DD hh:mm:ss"
									value-format="YYYY-MM-DD hh:mm:ss" 
									placeholder="请选择借阅时间" />
				</el-form-item>
				<el-form-item  label="归还时间" prop="return_time">
					<el-date-picker v-model="formData.return_time" 
									type="datetime" 
									format="YYYY-MM-DD hh:mm:ss"
									value-format="YYYY-MM-DD hh:mm:ss" 
									placeholder="请选择归还时间" />
				</el-form-item>
			</el-form>
		</div>
		<div class="form-box" v-if="['act_info','audit_art'].includes(dialogStatus)" v-loading="loading2">
			<el-descriptions size="default" :column="1" border>
				<el-descriptions-item label-class-name="labelC1" 
					label="合同名称：">
					<el-link  type="primary" @click="openDialog('Udetail',dataInfo.contract)">
						{{dataInfo.contract?.title}}
					</el-link>
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="申请人：">{{dataInfo.user?.name}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="审核人：">{{dataInfo.check?.name}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="借阅时间：">{{dataInfo.add_time_text}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="归还时间：">
					<el-text v-if="dataInfo.return_time_text" type="primary">{{dataInfo.return_time_text}}</el-text>
					<el-text  v-else type="warning">未归还</el-text></el-descriptions-item>
			</el-descriptions>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button v-if="['act_info'].includes(dialogStatus)" :disabled="loading3" @click="closeDialog">关
					闭</el-button>
				<el-button v-if="['act_edit','act_add'].includes(dialogStatus)" type="primary" :loading="loading3"
					@click="handleSubmit">{{dialogStatus == 'act_edit'?'重新提交':'确 定'}}</el-button>
				<el-button v-if="['act_edit','act_add','audit_art'].includes(dialogStatus)" :disabled="loading3"
					@click="closeDialog">取 消</el-button>
			</div>
		</template>
		
		
		<engineSelect v-if="binddialogSelect.visible" v-model="binddialogSelect.visible"
			:dialogTitle="binddialogSelect.title" @selectRowEngin="selectRowEngin"></engineSelect>
		
		<!-- 合同详情 -->
		
		<contractEdit
			v-if="dialogAdd.visible"
			v-model="dialogAdd.visible"
			:dialogTitle="dialogAdd.title"
			:dialogTableValue="dialogAdd.value"
			:dialogStatus="dialogAdd.status"
			 @initRefreshList="handleQuery">
		</contractEdit>
	</el-dialog>
</template>
<script setup lang="ts">
	import { useRoute } from 'vue-router';
	import _ from 'lodash-es'
	import { feilType } from "@/utils/funcall"
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	const baseConfigStore = useBaseConfigStore();
	import { BUSINESS_TYPE } from "@/utils/constant";
	import engineSelect from "./engineSelect.vue"
	import contractEdit from "./contractEdit.vue"
	
	import {
		addContractBorrow,
		updataContractBorrow,
		getContractBorrowDetail,
	} from "@/api/contract";
	//接口地址
	import {
		getDepartmentAndUser
	} from "@/api/doc";
	const props = defineProps({
		//数据列表索引值  例如 user ->对应着 vuex  == user_cxxxxx模块
		dialogTitle: {
			type: String,
			default: "添加信息"
		},
		dialogStatus: {
			type: String,
			default: "act_add"
		},
		dialogTableValue: {
			type: Object,
			default: () => { },
		}
	});
	const titModel = ref([{
		title: '待审核',
		type: 'info',
		value: 0
	}, {
		title: '已通过',
		type: 'success',
		value: 1
	}, {
		title: '已驳回',
		type: 'danger',
		value: 2
	}])
	const emit = defineEmits(['update:modelValue', 'initRefreshList']);
	const dialogVisible = ref(false);
	const loading2 = ref(false);//新增或者修改加载load按钮
	const loading3 = ref(false);//新增或者修改加载load按钮
	// 数据的data-ref
	const dataFormRef = ref(ElForm);
	const dataInfo = ref<any>({});
	const selectRow = ref<any>({});
	const formData = ref<any>({
		id: undefined,
		contract_id: "",//合同id
		uid: "",//申请人id
		check_uid: "",//审核人id
		add_time: "",//借阅时间
		return_time: "" //归还时间
	})
	const rules = reactive<any>({
		contract_id: [{ required: true, message: '请选择合同', trigger: 'change' }],
		uid: [{ required: true, message: '请选择申请人', trigger: 'change' }],
		check_uid: [{ required: true, message: '请选择审核人', trigger: 'change' }],
		add_time: [{ required: true, message: '请选择借阅时间', trigger: 'change' }],
		
	})
	const dialogAdd = reactive<any>({
		title: "查看详情", //弹窗标题
		visible: false,   //弹窗显示or隐藏
		status:"act_add", //弹窗状态类型 
		value:{}   		  //携带整条参数 row
	});
	// 打开新增表单内容
	function openDialog(type?:string, item ?: any) {
		if (type == "Udetail") {
			dialogAdd.title = '查看合同';
			dialogAdd.status = "Udetail"
			dialogAdd.value = item;
			dialogAdd.visible = true;
		}
	}
	watch(
		() => props.dialogTableValue,
		() => {
			if (props.dialogStatus == "audit_art") {
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else if (props.dialogStatus == "act_info") {
				console.log('查看详情')
				// getDetailInfo(props.dialogTableValue)
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else if (props.dialogStatus == "act_edit") {
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else {
				console.log('添加信息')
			}
		}, { deep: true, immediate: true })




	// users: [{ required: true, message: '请选择审批人', trigger: 'blur' }],
	// 提交新增内容/or修改
	function handleSubmit() {
		dataFormRef.value.validate((valid : boolean) => {
			console.log(valid)
			if (valid) {
				loading3.value = true;
				let data : any = {
					id: formData.value.id,
					contract_id:formData.value.contract_id,
					uid:formData.value.uid,
					check_uid:formData.value.check_uid,
					add_time:formData.value.add_time,
					return_time:formData.value.return_time
				}
				if (formData.value.id) {
					ElMessageBox.confirm("确定要修改信息?", "警告", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
					}).then(() => {
						updataContractBorrow(data).then((res) => {
							console.log(res)
							emit('initRefreshList');
							loading3.value = false;
							ElMessage({ message: '修改成功', type: 'success', duration: 1000 })
							closeDialog();
						}).finally(() => {
							loading3.value = false;
						})
					}).catch(() => {
						loading3.value = false;
					});
				}
				else {
					addContractBorrow(data).then((res) => {
						console.log(res)
						emit('initRefreshList');
						loading3.value = false;
						ElMessage({ message: '添加成功', type: 'success', duration: 1000 })
						closeDialog();
					}).finally(() => {
						loading3.value = false;
					})
				}
			}
		});
	}



	// 关闭弹窗
	function closeDialog() {
		if (!loading3.value) {
			emit('update:modelValue', false)
		}
	}

	// 获取详情
	function getAuditDetail(row) {
		loading2.value = true;
		getContractBorrowDetail({ id: row.id }).then((res) => {
			console.log(res.data)
			let data = res.data;

			formData.value.id = res.data.id;
			formData.value.contract_id = res.data.contract.id;
			formData.value.uid = res.data.uid;
			formData.value.check_uid = res.data.check_uid;
			formData.value.add_time = res.data.add_time_text;
			formData.value.return_time = res.data.return_time_text;
			
			dataInfo.value = res.data;
			selectRow.value = res.data.contract;

		}).finally(() => {
			loading2.value = false;
		})
	}

	/**
	 * 获取审批人列表
	 */
	const options = ref();
	/**
	 * 获取审批人列表
	 */
	function getShenPlist() {
		getDepartmentAndUser().then((res) => {
			options.value = res.data
		}).finally(() => { })
	}
	const binddialogSelect = reactive<any>({
		title: "选择合同", //弹窗标题
		visible: false,   //弹窗显示or隐藏
		status: "act_add", //弹窗状态类型  
		value: {}   		  //携带整条参数 row
	});
	// 绑定合同
	function bindGongCheng() {
		binddialogSelect.visible = true;
	}
	// 合同的回调函数
	function selectRowEngin(row) {
		console.log(row)
		selectRow.value = row;
		formData.value.contract_id = row.id;
	}
	
	
	onMounted(() => {
		getShenPlist();//获取审批人列表

	});
</script>

<style lang="scss" scoped>

</style>